import datetime
import json

import pymysql
from django.http import JsonResponse
from rest_framework import exceptions
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.throttling import SimpleRateThrottle
from rest_framework.views import APIView

from mall.utils.aliexpress_app_api import new_details, get_sku_attr
from mall.utils.get_freight_json import get_freight_json
from task.models import ShopTask, TaskQuest
from task.serializers import CreateBrowseTaskSerializer, CreateShopTaskSerializer, TaskQuestSerializer
from users.models import User


class MySimpleRateThrottle(SimpleRateThrottle):
    scope = "sku"

    def get_cache_key(self, request, view):
        return self.get_ident(request)


class Sku(APIView):
    throttle_classes = [MySimpleRateThrottle, ]  # 自定义分流类

    # 权限认证
    permission_classes = (IsAuthenticated,)

    def get(self, request, product_id):
        # TODO 添加国别不同产品价格不同的区别
        # 判断产品ID是否符合要求
        if not (product_id.isdigit() and len(product_id) in (11, 13)):
            return Response({'status': 'failed'})
        json_response = get_sku_attr.run(product_id)
        json_response_dict = json.loads(json_response)
        # 判断请求是否正常
        data = {}
        if bool(json_response_dict['data']):
            # 返回sku_attr,skuStock
            response = [{
                'skuAttr': i['skuAttr'],
                'skuStock': i['skuStock'],
                'skuAmount': i['skuActivityPriceVO'] if i.get('skuActivityPriceVO', None) else i['skuAmount'],
                'sellerAdminSeq': i['sellerAdminSeq']
            }
                for i in json_response_dict['data']['priceList']]
            data['status'] = 'successful'
            data['result_li'] = response
            return Response(data)
        else:
            data['status'] = 'failed'
            return Response(data)

    def throttled(self, request, wait):
        class MyThrottled(exceptions.Throttled):
            default_detail = '请求被限制.'
            extra_detail_singular = 'Expected available in {wait} second.'
            extra_detail_plural = '还需要再等待{wait}'

        raise MyThrottled(wait)


# TODO 添加搜索关键词审核
# data data global data
class ProductView(APIView):

    def get(self, request, product_id):
        # 判断产品ID是否符合要求
        try:
            if not (product_id.isdigit() and len(product_id) in (11, 13)):
                return Response({'status': 'failed'})
            details_json = new_details.run(product_id)
            details_dict = json.loads(details_json)
            data = dict()
            data['appImageUrl'] = details_dict['data']['data']['global']['data']['productInfo']['appImageUrl'][0]
            data['storeName'] = details_dict['data']['data']['global']['data']['sellerInfo']['storeName']
            return Response(data)
        except Exception as e:
            return Response({'status': 'failed'})


class FreightName(APIView):

    def get(self, request, product_id):
        # 判断产品ID是否符合要求
        if not (product_id.isdigit() and len(product_id) in (11, 13)):
            return Response({'status': 'failed'})
        # 判断购买数量字段
        sku_count = request.GET.get('count', 1)
        if not (sku_count.isdigit() and int(sku_count) < 999):
            return Response({'status': 'failed'})
        # 请求邮费接口
        json_response = get_freight_json(product_id, sku_count=sku_count)
        json_response_dict = json.loads(json_response)
        data = dict()
        if not json_response_dict['success']:
            data['status'] = 'failed'
            return Response(data)
        else:
            data['status'] = 'successful'
            data['result_dict'] = json_response_dict
            return Response(data)


class ShopTaskView(APIView):

    permission_classes = (IsAuthenticated,)

    def get(self, request):
        # 获取用户ID
        status = request.GET.get('status', None)
        if status:
            s = ShopTask.objects.filter(user_id_id=request.user.id, status=status)
        else:
            s = ShopTask.objects.filter(user_id_id=request.user.id)
        user_task_data = CreateShopTaskSerializer(s, many=True)
        # 通过用户ID获取对应的引流任务列表
        # 返回响应
        return Response(user_task_data.data)

    def post(self, request):
        # 获取用户ID
        try:
            request.data['user_id'] = request.user.id
            request.data['status'] = 0
            a = CreateShopTaskSerializer(data=request.data)
            a.is_valid()
            a.save()
            return Response('ok')
        except Exception as e:
            print(e)
            print(a.errors)
            raise e
            return Response('failed')


class BrowseTaskView(APIView):

    def post(self, request):
        # TODO 获取用户ID
        request.data['user_id'] = request.user.id
        request.data['status'] = 0
        a = CreateBrowseTaskSerializer(data=request.data)
        a.is_valid()
        a.save()
        return Response('ok')


# TODO 返回任务详情接口
class TaskQuestView(APIView):
    def get(self, requests, task_id):
        # 校验任务ID是否为该用户所有

        # 查询所有任务ID对应的分配任务ID
        quest_id_query_set = TaskQuest.objects.filter(task_id=task_id)
        t = TaskQuestSerializer(quest_id_query_set, many=True)
        conn = pymysql.connect(
                host='192.168.20.4',
                port=3306,
                user='yyh',
                password='123456',
                database='cbecnew',
                charset='utf8'
            )
        cursor = conn.cursor()
        result_li = list()
        status_dict = {
            0: '等待执行',
            1: '执行中',
            3: '执行失败',
            4: '执行完成',
            20: '执行失败',
        }
        for i in t.data:
            sql = f'''SELECT q.StartTime,h.Country,h.Sex,h.BrithDay,l.InternalLevel,q.r_RunTime,q.r_OrderIds,q.TotalPayLimit,q.r_TotalPayValue,q.RunState FROM dbflowctrlquest as q 
left JOIN vmdbaccountinfo as a on a.Id=q.AccountId
left JOIN vmdbhuman as h on h.Id=a.HumanID
left join cbecnewlog.logbuyerlevelsummary as l on l.AccountId=q.AccountId and l.PeriodEnd=201912
WHERE q.Id={i['quest_id']}'''
            cursor.execute(sql)
            temp_dict = dict()
            temp = cursor.fetchone()
            temp_dict['计划开始时间'] = temp[0].strftime('%Y-%m-%d %H:%M:%S')
            temp_dict['国家'] = temp[1]
            temp_dict['性别'] = '男' if temp[2] == 1 else '女'
            temp_dict['年龄'] = (datetime.datetime.now() - temp[3]).days // 365
            temp_dict['等级'] = temp[4]
            temp_dict['实际开始时间'] = temp[5].strftime('%Y-%m-%d %H:%M:%S')
            temp_dict['订单号'] = temp[6]
            temp_dict['任务支付限制'] = float(temp[7]) if temp[7] else 0
            temp_dict['任务实际支付'] = temp[8] if temp[8] else 0
            temp_dict['运行状态'] = status_dict[temp[9]]
            result_li.append(temp_dict)
        cursor.close()
        conn.close()
        return JsonResponse(result_li, safe=False)
        # 链接数据库查询实际任务情况
        # 查询分配任务ID的情况（任务状态码，实际执行任务时间，返回订单号，返回实际执行时间，任务金额限制，实际支付金额）
        # 组成json响应返回


# TODO 批量任务
# 批量产品ID

# 批量关键词

# 套餐
